import { autorun } from '@formily/reactive';
import { TreeNode } from '@inbiz/core';
import { RenderDropableWidget, usePlugin, useTreeNode } from '@inbiz/react';
import { useMemo } from 'react';
import { observer } from '@formily/react';
const addPlugin = (IndexCode: string, pluginName: string) => ({
  componentName: 'Field',
  props: {
    type: 'void',
    title: '插槽区域',
    'x-decorator': 'Container',
    'x-decorator-props': {
      clickable: true,
    },
    'x-component': pluginName,
    'x-component-props': {
      IndexCode,
      direction: 'row',
      align: 'flex-start',
    },
  },
});

const ShowPlugin = observer(({ IndexCode, pluginName }: { IndexCode: string, pluginName: string }) => {
  const node = useTreeNode();
  const plugins = usePlugin(pluginName);
  const pluginData = useMemo(() => {
    let plugin = plugins.find(
      (item) => item?.props?.['x-component-props']?.IndexCode === IndexCode,
    ) as TreeNode;
    if (!plugin) {
      plugin = new TreeNode(addPlugin(IndexCode, pluginName));
      node.append(plugin);
    }
    autorun(() => {
      if (plugin.children?.length) {
        plugin.children.forEach((item, index) => {
          if (
            item.props?.['x-component'] === 'EformButton' ||
            item.props?.['x-component'] === 'EformButtonGroup'
          ) {
            let style = item.props?.['x-decorator-props']?.style;
            if (style === undefined) {
              style = {};
              item.props['x-decorator-props'].style = style;
            }
            if (style?.display === undefined) {
              if (index == 0 || plugin?.props?.['x-component-props']?.direction != 'row') {
                style.margin = '';
              } else {
                style.margin = '0px 0px 0px 10px';
              }
            }
          }
        });
      }
    });
    return [plugin];
  }, [node, plugins]);

  return <RenderDropableWidget node={pluginData} pluginName={pluginName} />;
});

export default ShowPlugin;
